package com.mgface.springdata.controller;

import com.mgface.springdata.entity.Bag;
import com.mgface.springdata.entity.Curriculum;
import com.mgface.springdata.entity.School;
import com.mgface.springdata.entity.Student;
import com.mgface.springdata.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author wanyuxiang
 * @version 1.0
 * @project springdataCollection
 * @create 2018-08-17 10:19
 **/
@RestController
//在引入JDBC或JPA依赖时，spring boot已经默认注入了事务管理的实例
@Transactional(rollbackFor = RuntimeException.class,propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT)
public class studentController {
    @Autowired
    private StudentRepository studentRepository;

    @GetMapping(value = "/select")
    public List<Student> selet() {
        Iterable<Student> iterable = studentRepository.findAll();
        List<Student> list = new ArrayList<>();
        iterable.forEach(list::add);
        return list;
    }

    @GetMapping(value = "/select/{name}")
    public List<Student> select(@PathVariable("name") String name) {
        return studentRepository.findByNameOrderByIdAsc(name);
    }
    @GetMapping(value = "/select_page")
    public Map<String, Object> selectPage() {
        Page<Student> result = studentRepository.findAllBy(new PageRequest(0, 10, new Sort(Sort.Direction.DESC, "id")));
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("data", result.getContent()); //获取具体查询内容
        resultMap.put("count", result.getTotalPages()); //获取总页数
        return resultMap;
    }

    @GetMapping(value = "/insert")
    public Student insert() {
        Student s = new Student();
        Bag bag = new Bag();
        bag.setName("shubao1");
        s.setBag(bag);
        Curriculum curriculum = new Curriculum();
        curriculum.setName("math");
        Set<Curriculum> set = new HashSet<>();
        set.add(curriculum);
        s.setCurriculum(set);

        School school = new School();
        school.setName("xiwang");
        s.setSchool(school);
        s.setName("zhangsan");
        return studentRepository.save(s);
    }
}
